package practice1_100;

public class Offer29 {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length==0) return new int[0];
        int colBeg=0,colEnd=matrix[0].length-1,rowBeg=0,rowEnd=matrix.length-1;
        int len=(colEnd+1)*(rowEnd+1);
        int [] res=new int[(colEnd+1)*(rowEnd+1)];
        int j=0;
        while(colBeg<=colEnd&&rowBeg<=rowEnd){
            for(int i=colBeg;i<=colEnd-1&&j<len ;i++){
                res[j]=matrix[rowBeg][i];
                j++;
            }
            for(int i=rowBeg;i<=rowEnd-1&&j<len;i++){
                res[j]=matrix[i][colEnd];
                j++;
            }
            for(int i=colEnd;i>=colBeg+1&&j<len;i--){
                res[j]=matrix[rowEnd][i];
                j++;
            }
            for(int i=rowEnd;i>=rowBeg+1&&j<len;i--){
                res[j]=matrix[i][colBeg];
                j++;
            }
            rowBeg++;rowEnd--;colBeg++;colEnd--;
        }
        if(matrix.length==matrix[0].length&&matrix.length%2==1){
            res[res.length-1]=matrix[matrix.length/2][matrix.length/2];
        }
        return res;
    }

    public static void main(String[] args) {
        //[1,2,3],[4,5,6],[7,8,9]  {1,2,3},{4,5,6},{7,8,9}
        int[] a=new Offer29().spiralOrder(new int[][]{{7,8,9}});
//        "32432".toCharArray()
//        Syste.m.out.println(5/2);
//        Integer.pa
    }
}
